package superconfig

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"os"
	"strconv"
	"strings"
	"time"
)

type authData struct {
	Scheme string
	Auth   string
}
type zookeeper struct {
	Host     string
	Port     int
	AuthData authData
}
type env struct {
	Name      string
	Zookeeper zookeeper
	Deploy    string
	Group     string
}
type superConfig struct {
	Env env
}

func parse(data []byte) (superConfig, error) {
	var Superconfig superConfig

	err := json.Unmarshal(data, &Superconfig)
	if err != nil {
		return Superconfig, err
	}
	return Superconfig, err
}

func readSuperConf() []byte {
	dir, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}

	// 需要区别win和unix
	f, err := os.Open(strings.Replace(dir, "\\", "/", -1) + "/superconf.json")
	if err != nil {
		log.Fatal("open file fail")
	}
	defer f.Close()
	fd, err := ioutil.ReadAll(f)
	if err != nil {
		log.Fatal("read file fail")
	}
	return fd
}

func SetUp() *ZkClient {
	m, err := parse(readSuperConf())
	if err != nil {
		log.Fatal("parse superconf.json fail")
	}
	log.Println(m.Env.Zookeeper.Host)
	zkClient := NewZkClient([]string{m.Env.Zookeeper.Host + ":" + strconv.Itoa(m.Env.Zookeeper.Port)})
	if zkClient != nil {
		log.Println("create client success")
	} else {
		log.Fatal("create client fail")
	}
	err = zkClient.Connect(60 * time.Second)
	if err != nil {
		log.Fatal("create connection fail")
	} else {
		log.Println("create connection success")
	}
	return zkClient
}

type RedisConfig struct {
	Addr     string `json:"Addr"`
	Password string `json:"Password"`
	DB       int    `json:"DB"`
	Weight   int    `json:"Weight"`
}

type RedisConfigs []RedisConfig

func ParseToRedisConfig(data []byte) (RedisConfigs, error) {
	var RedisConfigList RedisConfigs

	err := json.Unmarshal(data, &RedisConfigList)
	if err != nil {
		return RedisConfigList, err
	}
	return RedisConfigList, err
}
